<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="90%"
             append-to-body>
    <el-form ref="formRef"
             :model="formModel"
             :rules="formRules"
             label-width="140px">
      <el-form-item label="主题类型："
                    prop="type">
        <el-radio-group v-model="formModel.type">
          <el-radio-button :label="1">专病筛查主题</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动名称："
                    prop="name"
                    ref="name">
        <el-input v-model="formModel.name"
                  placeholder="请输入活动名称"
                  class="w-200"></el-input>
      </el-form-item>
      <el-form-item label="活动主题："
                    prop="themeId">
        <el-select v-model="formModel.themeId"
                   :disabled="dataThemeObj ? true : false"
                   placeholder="请选择活动主题"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'theme')}"
                   :loading="loadingTheme"
                   class="w-200"
                   @change="val=>handleSelect(val, 'theme')">
          <el-option v-for="item in activeThemeFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与活动厂家："
                    prop="factoryId">
        <el-select v-model="factoryId"
                   placeholder="请选择参与活动厂家"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'factory')}"
                   :loading="loading2"
                   class="w-200"
                   @change="val=>handleSelect(val, 'factory')">
          <el-option v-for="item in activityFilterFactory"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动关联权益："
                    prop="inviolableId"
                    ref="inviolableId">
        <el-select v-model="formModel.inviolableId"
                   placeholder="请选择活动关联权益"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'inviolable')}"
                   :loading="loading4"
                   class="w-200"
                   @change="val=>handleSelect(val, 'inviolable')">
          <el-option v-for="item in inviolableFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与活动药品：">
        <el-table :data="formModel.activityDrugList"
                  style="width: 100%"
                  border
                  tooltip-effect="highLight">
          <el-table-column label="全选"
                           align="center"
                           prop="isUp"
                           width="55">
            <template slot="header"
                      slot-scope="scope">
              <el-checkbox v-model="checkAll"
                           :indeterminate="tableIsIndeterminate"
                           @change="value=>handleChange(value, 'tableData', formModel.activityDrugList)"></el-checkbox>
            </template>
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isUp"
                           :true-label="1"
                           :false-label="0"
                           @change="value =>tableCheckboxChange(scope.row, 'tableData', formModel.activityDrugList)"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="factoryName"
                           label="厂家名称"
                           width="150"
                           align="center">
          </el-table-column>
          <el-table-column prop="drugType"
                           label="药品分类"
                           width="100"
                           align="center">
            <template slot-scope="scope">
              <el-tag type="success"
                      v-if="scope.row.drugType === 2">化学药</el-tag>
              <el-tag type="info"
                      v-if="scope.row.drugType === 3">中成药</el-tag>
              <el-tag type="danger"
                      v-if="scope.row.drugType === 4">保健品</el-tag>
              <el-tag type="warning"
                      v-if="scope.row.drugType === 5">器械</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="drugName"
                           label="药品名称"
                           width="150"
                           align="center">
          </el-table-column>
          <el-table-column prop="standard"
                           label="规格"
                           width="100"
                           align="center">
          </el-table-column>
          <el-table-column prop="drugPackage"
                           label="包装"
                           width="100"
                           align="center">
          </el-table-column>
          <el-table-column prop="salesScript"
                           label="销售导语">
          </el-table-column>
          <el-table-column prop="taboo"
                           label="禁忌症">
          </el-table-column>
          <el-table-column prop="functionalIndications"
                           label="功能主治">
          </el-table-column>
          <el-table-column prop="adverseReaction"
                           label="不良反应">
          </el-table-column>
          <el-table-column prop="isUp"
                           label="是否为新上架"
                           width="100"
                           align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isUp"
                           :true-label="1"
                           :false-label="0"></el-checkbox>
            </template>
          </el-table-column>

        </el-table>
      </el-form-item>

      <el-form-item label="推荐健康风险筛查项目："
                    prop="risk"
                    label-width="180px">
        <el-select v-model="riskIds"
                   placeholder="请选择健康风险筛查项目"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 'risk')}"
                   :loading="loading1"
                   class="w-200"
                   @change="val=>handleSelect(val, 'risk')">
          <el-option v-for="item in riskFilterList"
                     :key="item.healthCheckPackageId"
                     :label="item.name"
                     :value="item.healthCheckPackageId">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddTable(riskIds, 'risk')">新 增</el-button>
      </el-form-item>
      <el-form-item label="已选健康筛查项目："
                    label-width="140px">
        <el-table :data="formModel.themeHealthList"
                  style="width: 100%"
                  border>
          <el-table-column prop="name"
                           label="健康筛查项目"
                           width="300">
          </el-table-column>
          <el-table-column prop="salesScript"
                           label="销售话术">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salesScript"
                        type="textarea"
                        :disabled="scope.row.belongType === 2 ? false : true"
                        placeholder="请输入销售话术"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="100"
                           align="center">
            <!-- 1:主题自带信息  2：活动添加信息  3：用户添加信息 -->
            <!-- 2.能改；1.不能改 -->
            <template slot-scope="scope">
              <el-button type="danger"
                         v-if="scope.row.belongType === 1 || !scope.row.belongType"
                         :disabled="activityId ? false : true"
                         @click="delRow(formModel.themeHealthList, scope.$index, scope.row, 'screening', 'isDel')">移 除</el-button>

              <el-button type="danger"
                         v-else
                         @click="delRow(formModel.themeHealthList, scope.$index, scope.row, 'screening', '')">移 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 推荐器械 -->
      <el-form-item label="推荐器械：">
        <el-button type="primary"
                   @click="handleAdd('equipment')"
                   v-if="activityId">新 增</el-button>
        <el-table :data="formModel.apparatusRequestDtoList"
                  style="width: 100%"
                  border
                  class="mt-20">
          <el-table-column prop="drugName"
                           label="器械名称">
          </el-table-column>
          <el-table-column prop="logoUrl"
                           label="图片"
                           width="120"
                           align="center">
            <template slot-scope="scope">
              <el-image style="width: 80px; height: 80px"
                        :src="scope.row.logoUrl"
                        :preview-src-list="[scope.row.logoUrl]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="salesScript"
                           label="销售导语">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="150"
                           align="center">
            <template slot-scope="scope">
              <el-button type="danger"
                         :disabled="activityId ? false : true"
                         @click="delRow(formModel.apparatusRequestDtoList, scope.$index, scope.row, 'equipment')">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <equipment-dialog :equipmentDataObj="equipmentDataObj"
                          :equipmentDataList="formModel.apparatusRequestDtoList"
                          @childEquipmentData="childEquipmentData"
                          :visible.sync="isShowEquipment"
                          v-if="isShowEquipment"></equipment-dialog>
      </el-form-item>
      <!-- 推荐商品 -->
      <el-form-item label="推荐商品：">
        <el-button type="primary"
                   @click="handleAdd('shop')"
                   v-if="activityId">新 增</el-button>
        <el-table :data="formModel.sellDrugDtoList"
                  style="width: 100%"
                  border
                  class="mt-20">
          <el-table-column prop="drugType"
                           label="商品类别"
                           align="center"
                           width="120">
            <template slot-scope="scope">
              <el-tag type="success"
                      v-if="scope.row.drugType === 1">中药</el-tag>
              <el-tag type="success"
                      v-if="scope.row.drugType === 2">化学药</el-tag>
              <el-tag type="danger"
                      v-if="scope.row.drugType === 3">中成药</el-tag>
              <el-tag type="info"
                      v-if="scope.row.drugType === 4">保健品</el-tag>
              <el-tag type="warning"
                      v-if="scope.row.drugType === 5">器械</el-tag>
              <el-tag type="success"
                      v-if="scope.row.drugType === 6">健康筛查</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="drugName"
                           label="商品名称">
          </el-table-column>
          <el-table-column prop="logoUrl"
                           label="图片"
                           width="120"
                           align="center">
            <template slot-scope="scope">
              <el-image style="width: 80px; height: 80px"
                        :src="scope.row.logoUrl"
                        :preview-src-list="[scope.row.logoUrl]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="standard"
                           label="规格"
                           width="100"
                           align="center">
          </el-table-column>
          <el-table-column prop="drugPackage"
                           label="包装"
                           width="100"
                           align="center">
          </el-table-column>
          <el-table-column prop="functionalIndications"
                           label="功能主治">
          </el-table-column>
          <el-table-column prop="taboo"
                           label="禁忌">
          </el-table-column>
          <el-table-column prop="adverseReaction"
                           label="不良反应">
          </el-table-column>
          <el-table-column prop="salesScript"
                           label="销售话术">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="120"
                           align="center">
            <template slot-scope="scope">
              <el-button type="danger"
                         :disabled="activityId ? false : true"
                         @click="delRow(formModel.sellDrugDtoList, scope.$index, scope.row, 'shop')">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <shop-dialog :shopDataObj="shopDataObj"
                     :fileUpload="fileUpload"
                     :sellDrugDtoList="formModel.sellDrugDtoList"
                     @childShopData="childShopData"
                     :visible.sync=isShowShop
                     v-if="isShowShop">
        </shop-dialog>
      </el-form-item>
      <!-- 联合荐药 -->
      <el-form-item label="联合荐药：">
        <el-button type="primary"
                   @click="handleAdd('medicine')">新 增</el-button>
        <el-table :data="recommendMedicineRequestDtoList"
                  style="width: 100%"
                  border
                  class="mt-20">
          <el-table-column prop="drugType"
                           label="类别"
                           width="120">
            <template slot-scope="scope">
              <el-tag type="success"
                      v-if="scope.row.drugType === 2">化学药</el-tag>
              <el-tag type="dager"
                      v-if="scope.row.drugType === 3">中成药</el-tag>
              <el-tag type="warning"
                      v-if="scope.row.drugType === 4">保健品</el-tag>
              <el-tag type="info"
                      v-if="scope.row.drugType === 5">器械</el-tag>
              <el-tag type="dager"
                      v-if="scope.row.drugType === 6">健康筛查</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="value"
                           label="内容">
            <template slot-scope="scope">
              <el-tag type="success"
                      v-for="(item, index) in scope.row.value"
                      :key="index"
                      style="margin-right:5px">
                {{item.drugName}}--{{item.factoryName}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <table style="width: 100%"
               border="0"
               class="table-cell"
               cellspacing="0"
               cellpadding="0">
          <tr>
            <td width="121"
                class="first-td">
              <el-tag type="danger">健康筛查项目</el-tag>
            </td>
            <td>
              <el-tag v-for="item in formModel.themeHealthList"
                      :key="item.id"
                      type="danger"
                      style="margin-right:5px">
                {{item.name}}
              </el-tag>
            </td>
          </tr>
          <tr>
            <td width="121"
                class="first-td">
              <el-tag type="info">销售话术</el-tag>
            </td>
            <td>
              {{formModel.recommendSalesScript}}
            </td>
          </tr>
        </table>
        <medicine-dialog :medicineDataObj="medicineDataObj"
                         @childMedicineData="childMedicineData"
                         :activityId="activityId"
                         :visible.sync="isShowMedicine"
                         v-if="isShowMedicine"></medicine-dialog>
      </el-form-item>
      <el-form-item label="参与活动客户："
                    prop="companyId"
                    ref="companyId">
        <el-select v-model="formModel.companyId"
                   placeholder="请选择参与活动客户"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'activeCustomers')}"
                   :loading="loading5"
                   class="w-500"
                   @change="val=>handleSelect(val, 'activeCustomers')">
          <el-option v-for="item in activeCustomersFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联活动预约：">
        <el-select v-model="formModel.appointmentId"
                   placeholder="请选择关联活动预约"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'appointment')}"
                   :loading="loadingAppointment"
                   class="w-500"
                   @change="val=>handleSelect(val, 'appointment')"
                   :disabled="formModel.companyId !== '' ? false : true">
          <el-option v-for="item in appointmentFilterList"
                     :key="item.appointmentId"
                     :label="item.appointmentName"
                     :value="item.appointmentId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与分店：">
        <el-table :data="tableBranch"
                  border
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  ref="asTable"
                  height="460">
          <el-table-column width="50"
                           type="selection"
                           fixed="left">
          </el-table-column>
          <el-table-column prop="id"
                           label="ID">
          </el-table-column>
          <el-table-column prop="hospitalId"
                           label="医院ID">
          </el-table-column>
          <el-table-column prop="hospitalName"
                           label="分店名字">
          </el-table-column>
          <el-table-column prop="manager"
                           label="店长">
          </el-table-column>
          <el-table-column prop="phone"
                           label="联系方式">
          </el-table-column>
        </el-table>
        <p align="left"
           class="mt-20">
          <!-- 已选：{{ allMultipleSelection }} -->
          <el-pagination background
                         @current-change="handleCurrentChange"
                         :current-page.sync="pagination.pageIndex"
                         :page-size="pagination.pageSize"
                         layout="total, prev, pager, next, jumper"
                         :total="pagination.totalNum">
          </el-pagination>
        </p>
      </el-form-item>
      <el-form-item label="活动开始时间："
                    prop="beginTime"
                    ref="beginTime">
        <el-date-picker v-model="formModel.beginTime"
                        type="date"
                        value-format="timestamp"
                        clearable
                        placeholder="选择活动开始时间"
                        :picker-options="pickerOptionsStart">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动结束时间："
                    prop="finishTime"
                    ref="finishTime">
        <el-date-picker v-model="formModel.finishTime"
                        type="date"
                        value-format="timestamp"
                        clearable
                        placeholder="选择活动结束时间"
                        :picker-options="pickerOptionsEnd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="解读医院：">
        <el-select v-model="formModel.hospitalId"
                   placeholder="请选择解读医院"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'hospital')}"
                   :loading="loading6"
                   class="w-500"
                   @change="val=>handleSelect(val, 'hospital')">
          <el-option v-for="item in interpretationFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动关联检测项及参考值："
                    label-width="180px">
        <el-button type="primary"
                   @click="handleAddItem(maxNum++)">新 增</el-button>
        <!-- 全测指标 S -->
        <el-card class="card-box mt-20">
          <div slot="header">
            <span>全测指标：</span>
            <el-select v-model="everyDetectIds"
                       placeholder="请选择检测项"
                       filterable
                       remote
                       clearable
                       reserve-keyword
                       :remote-method="(query) => {remoteMethod2(query, 'everyItem')}"
                       :loading="loading44"
                       class="w-200"
                       @change="val=>handleSelect2(val, 'everyItem')">
              <el-option v-for="item in detectFilterList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
            <el-button type="primary"
                       @click="handleAddSelectVal(everyDetectIds, 'everyItem')">新 增</el-button>
          </div>
          <el-table :data="themeDeviceTableList1"
                    style="width: 100%"
                    border
                    :span-method="handleSpan">
            <el-table-column prop="deviceName"
                             label="检测项名称">
            </el-table-column>
            <el-table-column prop="referenceName"
                             label="检测指标">
            </el-table-column>
            <el-table-column prop="referenceValue"
                             label="参考值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.referenceValue"
                          placeholder="请输入参考值"
                          class="w-200"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="delField"
                             label="操作"
                             width="100"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delMergeRow(themeDeviceTableList1,  scope.row, 'everyItem')">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 全测指标 E -->
        <!-- 任选X项 S -->
        <div v-for="(item, index) in themeDeviceTable"
             :key="index">
          <el-card class="card-box mt-20">
            <div slot="header"
                 class="clearfix">
              <span class="fill-box">任选<el-input-number v-model="item.num"
                                 :controls="false"
                                 class="num"
                                 @change="changeItemVal"></el-input-number> 项：</span>

              <el-select v-model="item.someDetectIds"
                         placeholder="请选择检测项"
                         filterable
                         remote
                         clearable
                         reserve-keyword
                         :remote-method="(query) => {remoteMethod2(query, 'someItem')}"
                         :loading="loading33"
                         class="w-200"
                         @change="val=>handleSelect2(val, 'someItem')">
                <el-option v-for="el in detectFilterList"
                           :key="el.id"
                           :label="el.name"
                           :value="el.id">
                </el-option>
              </el-select>
              <el-button type="primary"
                         @click="handleAddSelectVal(item.someDetectIds, 'someItem', index, item.num, item.modelIndex)">新增检测项</el-button>
              <el-button type="danger"
                         style="float: right;"
                         @click="delRowItem(themeDeviceTable,  'someItem', index, item.num)">删除检测项</el-button>
            </div>
            <div v-if="item.themeDeviceDtoList">
              <el-table :data="item.themeDeviceDtoList"
                        style="width: 100%"
                        border
                        :key="index"
                        :span-method="handleSpan">
                <el-table-column prop="deviceName"
                                 label="检测项名称">
                </el-table-column>
                <el-table-column prop="referenceName"
                                 label="检测指标">
                </el-table-column>
                <el-table-column prop="referenceValue"
                                 label="参考值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.referenceValue"
                              placeholder="请输入参考值"
                              class="w-200"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="delField"
                                 label="操作"
                                 width="100"
                                 align="center">
                  <template slot-scope="scope">
                    <el-button type="danger"
                               @click="delMergeRow(item.themeDeviceDtoList, scope.row, 'someItem', index)">删 除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </div>
        <!-- 任选X项 E -->
      </el-form-item>
      <el-form-item label="相关检测项："
                    prop="detectIds"
                    label-width="180px">
        <el-select v-model="detectIds"
                   placeholder="请选择相关检测项"
                   filterable
                   remote
                   clearable
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod2(query, 'detect')}"
                   :loading="loading55"
                   class="w-200"
                   @change="val=>handleSelect2(val, 'detect')">
          <el-option v-for="item in detectFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <!-- 相关检测项 S -->
        <el-button type="primary"
                   @click="handleAddSelectVal(detectIds, 'detect')">新 增</el-button>
        <el-card class="card-box mt-20">
          <div slot="header"><span>相关检测项</span></div>
          <el-table :data="correlationDtoList"
                    style="width: 100%"
                    border
                    :span-method="handleSpan">
            <el-table-column prop="deviceName"
                             label="检测项名称">
            </el-table-column>
            <el-table-column prop="referenceName"
                             label="检测指标">
            </el-table-column>
            <el-table-column prop="referenceValue"
                             label="参考值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.referenceValue"
                          placeholder="请输入参考值"
                          class="w-200"></el-input>
              </template>
            </el-table-column>

            <el-table-column prop="delField"
                             label="操作"
                             width="100"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delMergeRow(correlationDtoList, scope.row, 'detect')">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 相关检测项 E -->
      </el-form-item>
      <el-form-item label="推荐医院检查项目："
                    label-width="200">
        <el-input v-model="formModel.recommendableProjects"
                  type="textarea"
                  style="width:calc(100% - 138px)"
                  placeholder="请输入推荐医院检查项目"></el-input>
      </el-form-item>
      <el-form-item label="C端用户签到权益："
                    label-width="180px"
                    prop="activityUserInviolableRightsDtos"
                    ref="activityUserInviolableRightsDtos">
        <el-button type="primary"
                   @click="handleAdd('equity')">新 增</el-button>
        <el-table :data="formModel.activityUserInviolableRightsDtos"
                  style="width: 100%"
                  border
                  height="300"
                  class="mt-20">
          <el-table-column prop="name"
                           label="权益名称"
                           width="180">
          </el-table-column>
          <el-table-column prop="content"
                           label="权益内容">
          </el-table-column>
          <el-table-column prop="sortNum"
                           width="100"
                           align="center"
                           label="前端排序">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="180">
            <template slot-scope="scope">
              <el-button type="primary"
                         @click="editRow(formModel.activityUserInviolableRightsDtos, scope.$index, 'equity')">编 辑</el-button>
              <el-button type="danger"
                         @click="removeRow(formModel.activityUserInviolableRightsDtos, scope.$index, 'equity')">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <equity-dialog :equityObj="equityObj"
                       @childEquityData="childEquityData"
                       :visible.sync="isShowEquity"
                       :inviolableTableData="formModel.activityUserInviolableRightsDtos"
                       :isShowEquityDetail="isShowEquityDetail"
                       v-if="isShowEquity"></equity-dialog>
      </el-form-item>
      <!-- 活动重点知识点 -->
      <el-form-item label="活动重点知识点："
                    label-width="240">
        <el-button type="primary"
                   @click="handleAdd('goods')">新 增</el-button>
        <p align="center"
           style="width:100%"
           v-if="goodsList.length === 0">
          <el-empty :image-size="100"></el-empty>
        </p>
        <el-card class="mt-20 knowledge-box"
                 v-else>
          <el-timeline>
            <el-timeline-item class="div-list"
                              v-for="(item, index) in goodsList"
                              :key="index">
              <div class="knowledge-main">
                <span v-html="commonFunction.highLight1(item.knowledge, item.keyWordList)">{{item.knowledge}}</span>

                <el-button type="primary"
                           @click="editRow(goodsList, index, 'goods')">编 辑</el-button>
                <el-button type="danger"
                           @click="removeRow(goodsList, index, 'goods')">删 除</el-button>
              </div>
              <ul v-if="item.knowledgeImage"
                  class="knowledgeImage-list">
                <li v-for="(list, i) in item.knowledgeImage"
                    :key="i">
                  <el-image style="width: 120px; height: 120px"
                            :src="list"
                            :preview-src-list="item.knowledgeImage">
                  </el-image>
                  <i class="del el-icon-error"
                     @click="removeRow(item.knowledgeImage, i)"></i>

                </li>
              </ul>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <goods-dialog :goodsDataObj="goodsDataObj"
                      @childGoodsData="childGoodsData"
                      :isShowDetail="isShowDetail"
                      :visible.sync="isShowGoods"
                      v-if="isShowGoods"></goods-dialog>
      </el-form-item>
      <!-- 活动关联知识点 -->
      <el-form-item label="活动关联知识点："
                    label-width="240">
        <el-button type="primary"
                   @click="handleAdd('knowledge')">新 增</el-button>
        <p align="center"
           style="width:100%"
           v-if="knowledgeList.length === 0">
          <el-empty :image-size="100"></el-empty>
        </p>
        <el-card class="mt-20 knowledge-box"
                 v-else>
          <el-timeline>
            <el-timeline-item class="div-list"
                              v-for="(item, index) in knowledgeList"
                              :key="index">
              <div class="knowledge-main">
                <span v-html="commonFunction.highLight1(item.knowledge, item.keyWordList)">{{item.knowledge}}</span>
                <el-button type="primary"
                           @click="editRow(knowledgeList, index, 'knowledge')">编 辑</el-button>
                <el-button type="danger"
                           @click="removeRow(knowledgeList, index, 'knowledge')">删 除</el-button>
              </div>
              <ul v-if="item.knowledgeImage"
                  class="knowledgeImage-list">
                <li v-for="(list, i) in item.knowledgeImage"
                    :key="i">
                  <el-image style="width: 120px; height: 120px"
                            :src="list"
                            :preview-src-list="item.knowledgeImage">
                  </el-image>
                  <i class="del el-icon-error"
                     @click="removeRow(item.knowledgeImage, i)"></i>
                </li>
              </ul>
            </el-timeline-item>
          </el-timeline>
        </el-card>
        <knowledge-dialog :knowledgeDataObj="knowledgeDataObj"
                          @childKnowledgeData="childKnowledgeData"
                          :isShowDetail="isShowDetail"
                          :visible.sync="isShowKnowledge"
                          v-if="isShowKnowledge"></knowledge-dialog>
      </el-form-item>

      <el-form-item label="活动介绍："
                    label-width="140px">
        <div ref="editor"
             class="editor">
          <vue-neditor-wrap :destroy="true"
                            v-model="formModel.introduce"
                            :config="myConfig"></vue-neditor-wrap>

        </div>
      </el-form-item>
      <el-form-item label="知识点每日学习次数："
                    label-width="180px">
        <el-input v-model="formModel.activityStudyTime"
                  placeholder="请输入学习次数"
                  :min="0"
                  class="w-200">
          <template slot="append">元/人</template>
        </el-input>
      </el-form-item>
      <el-form-item label="产品药店资料每日学习次数："
                    label-width="200px">
        <el-input v-model="formModel.activityDrugStudyTime"
                  placeholder="请输入学习次数"
                  :min="0"
                  class="w-200">
          <template slot="append">人</template>
        </el-input>
      </el-form-item>
    </el-form>
    <p align="center"
       class="mt-20">
      <el-button type="info"
                 @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="submitForm">保 存</el-button>
    </p>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import VueNeditorWrap from 'vue-neditor-wrap'
  import equipmentDialog from './equipmentDialog' // 推荐器械
  import shopDialog from './shopDialog' // 推荐商品
  import medicineDialog from './medicineDialog' // 联合荐药
  import knowledgeDialog from './knowledgeDialog' // 活动关联知识点
  import goodsDialog from './goodsDialog' // 活动关联重点知识点
  import equityDialog from './setEquityDialog' // C端用户签到权益
  export default {
    name: 'themeDialog', // 主题任务发布
    props: {
      dataThemeObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        title: '新增主题任务发布',
        loading: false,
        loading1: false, // 推荐健康风险筛查项目默认false
        loading2: false,

        loading4: false,
        loading5: false,
        loading6: false,
        loading33: false, // 任选X项
        loading44: false, // 全测指标
        loading55: false, // 相关检测项
        loadingAppointment: false, // 关联活动预约
        loadingTheme: false, // 活动主题
        formModel: {
          type: 1, // 主题类型
          name: '', // 活动名称
          activityId: null,
          themeId: '', // 活动主题
          inviolableId: null, // 权益id，当编辑的时候，为活动权益id
          companyId: '', // 参与活动客户
          appointmentId: 0, // 关联活动预约
          hospitalIds: [],  // 参与分店
          beginTime: '', // 活动开始时间
          finishTime: '', // 活动结束时间
          hospitalId: '', // 解读医院
          recommendableProjects: '', // 推荐医院检查项目
          themeHealthList: [],  // 已选健康筛查项目
          recommendMedicineRequestDtoList: [], // 联合荐药列表
          recommendSalesScript: '', // 销售话术
          themeKnowledgeRequestDtoList: [], // 知识点、活动商品卖点
          activityDrugList: [], // 参加活动药品信息
          themeDeviceDtoList: [], // 必测检测项、相关检测项
          introduce: '', // 活动介绍
          activityStudyTime: undefined, // 知识点每日学习次数
          activityDrugStudyTime: undefined, // 产品药店资料每日学习次数
          activityUserInviolableRightsDtos: [], // C端用户签到权益
        },
        recommendMedicineRequestDtoList: [],
        knowledgeList: [], // 知识点
        goodsList: [], // 活动商品卖点
        isShowDetail: false,
        isShowEquityDetail: false,
        // 活动主题
        activeThemeList: [],
        activeThemeFilterList: [],
        // 活动关联权益
        inviolableList: [],
        inviolableFilterList: [],
        // 解读医院
        interpretationList: [],
        interpretationFilterList: [],
        formRules: {
          name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
          themeId: [{ required: true, message: '请选择活动主题', trigger: 'change' }],
          // factoryIds: [{ required: true, message: '请选择参与活动厂家', trigger: 'blur' }],
          beginTime: [{ type: 'date', required: true, message: '选择活动开始时间', trigger: ['blur', 'chagne'] }],
          finishTime: [{ type: 'date', required: true, message: '选择活动结束时间', trigger: ['blur', 'chagne'] }],
          companyId: [{ required: true, message: '请选择参与活动客户', trigger: 'blur' }],
          inviolableId: [{ required: true, message: '请选择活动关联权益', trigger: 'blur' }],
          activityUserInviolableRightsDtos: [{ required: true, message: '请配置C端用户签到权益', trigger: 'blur' }]
        },

        // 推荐健康风险筛查项目
        riskList: [],
        riskFilterList: [],
        factoryId: [], // 参与活动厂家
        riskIds: [], // 推荐健康风险筛查项目
        // 全选标志
        checkAll: false,
        // 半选标志
        tableIsIndeterminate: false,
        isShowEquipment: false, // 推荐器械
        isShowShop: false, // 推荐商品
        isShowMedicine: false, // 联合荐药
        isShowKnowledge: false, // 知识点
        isShowGoods: false, // 活动商品卖点
        isShowEquity: false, // C端用户签到权益
        equipmentDataObj: {}, // 推荐器械
        shopDataObj: {}, // 推荐商品
        medicineDataObj: {}, // 联合荐药
        knowledgeDataObj: {}, // 知识点
        goodsDataObj: {}, // 活动商品卖点
        equityObj: {}, // C端用户签到权益
        // 参与活动客户
        activeCustomersList: [],
        activeCustomersFilterList: [],
        // 关联活动预约
        appointmentList: [],
        appointmentFilterList: [],
        // 参与活动客户
        branchList: [],
        branchFilterList: [],
        // 参与分店
        tableBranch: [],

        multipleSelection: [],
        allMultipleSelection: [],
        pagination: {
          pageIndex: 1,
          pageSize: 10
        },
        typeList: [
          { drugType: 2, drugName: "化学药" },
          { drugType: 3, drugName: "中成药" },
          { drugType: 4, drugName: "保健品" },
          { drugType: 5, drugName: "器械" }
        ],
        childMedicineTableData: [],
        pageIndex: 1,
        pageSize: 10,
        // 参与活动厂家
        activityFactory: [],
        activityFilterFactory: [],
        activityId: '',
        activityInviolableId: null,  // 活动权益id
        pickerOptionsStart: {
          disabledDate: time => {
            const endDateVal = new Date(this.formModel.finishTime).getTime()
            if (endDateVal) {
              return time.getTime() > endDateVal - 0
            }
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            const beginDateVal = new Date(this.formModel.beginTime).getTime()
            if (beginDateVal) {
              return time.getTime() < beginDateVal - 0
            }
          }
        },
        myConfig: {
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: '418',
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: false,
          scaleEnabled: true
        },
        // 必测检测项
        detectList: [],
        detectFilterList: [],
        themeDeviceTable: [],
        themeDeviceTableList1: [], //
        correlationDtoList: [], // 相关检测
        detectIds: '', // 相关检测项
        everyDetectIds: '', // 全测指标
        someDetectIds: '', // 任选X项
        maxNum: 1,
        inviolableTableData: []
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      submitForm () {
        this.formModel.themeKnowledgeRequestDtoList = [...this.knowledgeList, ...this.goodsList];
        this.formModel.themeKnowledgeRequestDtoList.forEach(item => {
          if (item.knowledgeImageUrls) {
            item.knowledgeImageUrls = JSON.stringify(item.knowledgeImage);
          }
        })
        this.formModel.hospitalIds = this.allMultipleSelection;
        // 必测检测项、相关检测项
        let tempDataList = [];
        this.themeDeviceTable.forEach(item => {
          item.themeDeviceDtoList.forEach(item2 => {
            tempDataList.push(item2);
          });
        });
        this.formModel.themeDeviceDtoList = [...this.themeDeviceTableList1,
        ...tempDataList, ...this.correlationDtoList];
        if (this.themeDeviceTableList1.length === 0) {
          this.$message.error('必测检测项至少添加一项!');
          return
        }
        // 联合荐药
        let recommendMedicine = []
        this.recommendMedicineRequestDtoList.forEach(item => {
          item.value.forEach(list => {
            recommendMedicine.push(list);
          })
        })
        this.formModel.recommendMedicineRequestDtoList = recommendMedicine;
        let activityDrugList = this.formModel.activityDrugList;
        if (activityDrugList.length === 0) {
          this.$message.error('请至少选择一个参与活动厂家!');
          return
        }
        let flag = activityDrugList.some(item => {
          if (item.isUp === 1) {
            return true;
          }
        })
        if (!flag) {
          this.$message.error('至少勾选一项参与活动药品!');
          return
        }
        if (this.formModel.companyId === '') {
          // this.$message.error('请选择参与活动客户!');
          // return
        } else {
          if (this.multipleSelection.length === 0) {
            this.$message.error('至少勾选一家参与分店!');
            return
          }
        }
        if (this.goodsList.length === 0) {
          this.$message.error('活动重点知识点不能为空!');
          return
        }

        // 关联活动预约
        if (this.formModel.appointmentId) {
        } else {
          this.formModel.appointmentId = 0;
        }
        this.$refs.formRef.validate(async (valid, object) => {
          if (valid) {
            if (this.dataThemeObj) {
              const { data: res } = await this.post(this.api.promote.updateActivity, this.formModel, { showFullScreenLoading: true });
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.modalClose();
                this.$parent.getList();
              }
            } else { // 新增
              const { data: res } = await this.post(this.api.promote.activityPublish, this.formModel, { showFullScreenLoading: true });
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.modalClose();
                this.$parent.getList();
              }
            }

          } else {
            for (let i in object) {
              let dom = this.$refs[i];
              if (Object.prototype.toString.call(dom) !== '[object Object]') { // 这里是针对遍历的情况（多个输入框），取值为数组
                dom = dom[0]
              }
              // 第一种方法（包含动画效果）
              dom.$el.scrollIntoView({　　// 滚动到指定节点
                block: 'center',　　　　　// 值有start,center,end，nearest，当前显示在视图区域中间
                behavior: 'smooth'　　　　// 值有auto、instant,smooth，缓动动画（当前是慢速的）
              })
              break; // 因为我们只需要检测一项,所以就可以跳出循环了
            }
          }
        })
      },

      // 全选或全不选
      handleChange (val, op, table) {
        switch (op) {
          case 'tableData':
            if (val) {
              table.forEach(item => {
                item.isUp = 1;
              });
              this.tableIsIndeterminate = false;
            } else {
              table.forEach(item => {
                item.isUp = 0;
              });
              this.tableIsIndeterminate = false;
            }
            break;
        }

      },
      /**
       * @name: 全选 checkbox部分选择
       * @event: change
       * 1、isAllTrue：checkAll为true，为全选标志，tableIsIndeterminate为false，半选标志不显示
       * 2、isAllFalse：checkAll为false，无标志，tableIsIndeterminate为false，半选标志不显示
       * 3、其他情况，为半选标志
       */

      tableCheckboxChange (val, op, table) {
        switch (op) {
          case 'tableData':
            setTimeout(() => {
              let isAllTrue = table.every(item => item.isUp === true);
              let isAllFalse = table.every(item => item.isUp === false);
              if (isAllTrue) {
                this.tableIsIndeterminate = false;
                this.checkAll = true;
              } else if (isAllFalse) {
                this.tableIsIndeterminate = false;
                this.checkAll = false;
              } else {
                this.checkAll = false;
                this.tableIsIndeterminate = true;
              }
            }, 0);
            break;
        }

      },
      // 删除已选健康筛查项目
      delRow (table, index, row, op, type) {
        if (op === 'screening') {
          if (type === 'isDel') {
            this.$confirm('确认删除？')
              .then(_ => {
                this.post(this.api.promote.delActivityHealth, { id: row.id }).then(res => {
                  if (res.data.code === '200') {
                    this.$message.success('删除成功!');
                    table.splice(index, 1);
                  }
                })
              })
              .catch(_ => { });
          } else {
            table.splice(index, 1);
          }
        }
        if (op === 'equipment' || op === 'shop') {
          this.$confirm('确认删除？')
            .then(_ => {
              this.post(this.api.promote.delActivityDrug, { id: row.id }).then(res => {
                if (res.data.code === '200') {
                  this.$message.success('删除成功!');
                  table.splice(index, 1);
                }
              })
            })
            .catch(_ => { });
        }

      },
      handleAdd (option) {
        switch (option) {
          // 器械
          case 'equipment':
            this.isShowEquipment = true;
            this.equipmentDataObj = this.formModel;
            break;
          // 推荐商品
          case 'shop':
            this.isShowShop = true;
            this.shopDataObj = this.formModel;
            break;
          // 联合荐药
          case 'medicine':
            this.isShowMedicine = true;
            // this.medicineDataObj = this.formModel;
            let { recommendSalesScript, recommendMedicineRequestDtoList } = this.formModel;
            let data = this.childMedicineTableData;
            this.medicineDataObj = {
              recommendSalesScript: recommendSalesScript,
              recommendMedicineRequestDtoList: data.length === 0 ? recommendMedicineRequestDtoList : data
            };
            break;
          case 'knowledge':
            this.isShowKnowledge = true;
            this.isShowDetail = false;
            break;
          case 'goods':
            this.isShowGoods = true;
            this.isShowDetail = false;
            break;
          // C端用户签到权益
          case 'equity':
            this.isShowEquity = true;
            this.isShowEquityDetail = false;

            break
        }
      },
      // 推荐器械,接收子组件传递过来的数据
      childEquipmentData (data) {
        this.formModel.apparatusRequestDtoList.push(data);
      },
      // 推荐商品,接收子组件传递过来的数据
      childShopData (data) {
        this.formModel.sellDrugDtoList.push(data);
      },
      // 联合荐药,接收子组件传递过来的数据
      childMedicineData (data) {
        this.childMedicineTableData = data.tableData;
        this.formModel.recommendSalesScript = data.recommendSalesScript;
        const result = this.typeList.map(item => ({
          ...item,
          value: data.tableData.filter(sItem => item.drugType === sItem.drugType)
        }))
        this.recommendMedicineRequestDtoList = result;
      },
      // 知识点,接收子组件传递过来的数据
      childKnowledgeData (data) {
        if (data.isEdit) {
          this.knowledgeList[[data.key]] = data;
        } else {
          this.knowledgeList.push(data);
        }
        this.knowledgeList.forEach(item => {
          item.keyWord = item.keyWordList.join(',');
        })
      },
      // 活动商品卖点,接收子组件传递过来的数据
      childGoodsData (data) {
        if (data.isEdit) {
          this.goodsList[[data.key]] = data;
        } else {
          this.goodsList.push(data);
        }
        this.goodsList.forEach(item => {
          item.keyWord = item.keyWordList.join(',');
        })
      },
      // C端用户签到权益
      childEquityData (data) {
        console.log("data",data)

        if (data.isEdit) {

          const obj = this.formModel.activityUserInviolableRightsDtos.find(item => item.activityId === data.activityId);
          console.log("obj",obj)
          if (obj.sortNum <= data.sortNum) {
            this.formModel.activityUserInviolableRightsDtos.forEach(item => {
              if (item.sortNum >= data.sortNum) {
                item.sortNum += 1;
              }
            })
          } else {
            this.formModel.activityUserInviolableRightsDtos.forEach(item => {
              if (obj.sortNum > item.sortNum && item.sortNum >= data.sortNum) {
                item.sortNum += 1;
              }
            })
          }
          var bean={
            "name": "",
            "content": "",
            "sortNum": '',
            "isEdit": true,
            "key": ''
          }
          this.formModel.activityUserInviolableRightsDtos[[data.key]] = Object.assign(bean,data);
          this.$forceUpdate()
          console.log("最后数据",this.formModel.activityUserInviolableRightsDtos)
        } else {
          this.formModel.activityUserInviolableRightsDtos.forEach(item => {
            if (item.sortNum >= data.sortNum) {
              item.sortNum += 1;
            }
          })
          this.formModel.activityUserInviolableRightsDtos.push(data);
        }

      },
      // 查询分店
      fetchData () {
        this.post(this.api.company.hospitalList, {
          pageIndex: this.pagination.pageIndex - 1,
          pageSize: this.pagination.pageSize,
          searchCondition: '',
          companyId: this.formModel.companyId
        }).then(res => {
          if (res.data.code === '200') {
            setTimeout(_ => {
              this.tableBranch = res.data.object;
              this.pagination.totalNum = res.data.totalNum;
              // 实现分页复选
              setTimeout(_ => {
                this.setSelectedRow();
              }, 50)
            }, 200)
          }
        })
      },
      setSelectedRow () {
        // 设置当前页已选项
        this.tableBranch.forEach(item => {
          if (this.allMultipleSelection.includes(item.hospitalId)) {
            this.$refs.asTable.toggleRowSelection(item, true);
            // console.log(item.id, 'set');
          }
        })
      },
      handleCurrentChange (val) {
        this.pagination.pageIndex = val;
        this.fetchData();
      },

      handleSelectionChange (val) {
        this.multipleSelection = val;
        // 实现分页复选
        setTimeout(_ => {
          this.resolveAllSelection();
        }, 50);
      },
      resolveAllSelection () {
        let currentPageData = this.tableBranch.map(item => item.hospitalId); // 当前页所有数据
        let currentPageSelected = this.multipleSelection.map(item => item.hospitalId); // 当前页已选数据
        let currentPageNotSelected = currentPageData.filter(item => !currentPageSelected.includes(item)); // 当前页未选数据
        // 将当前页已选数据放入所有已选项
        currentPageSelected.forEach(item => {
          if (!this.allMultipleSelection.includes(item)) {
            this.allMultipleSelection.push(item);
          }
        })
        // 将所有已选项数据中当前页没选择的项移除
        currentPageNotSelected.forEach(item => {
          let idx = this.allMultipleSelection.indexOf(item);
          if (idx > -1) {
            this.allMultipleSelection.splice(idx, 1);
          }
        })
      },
      // 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'factory') {
              _this.loading2 = true; // 锁住
              this.post(this.api.promote.factoryList, {
                search: query,
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading2 = false;
                  _this.activityFactory = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading2 = false;
                _this.activityFilterFactory = _this.activityFactory.filter(item => item.name.indexOf(query) > -1);
              }, 200);
            }
            if (type === 'theme') {
              _this.loadingTheme = true; // 锁住
              this.post(this.api.promote.themeInfoList, {
                search: query,
                type: this.formModel.type,
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loadingTheme = false;
                  _this.activeThemeList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loadingTheme = false;
                _this.activeThemeFilterList = _this.activeThemeList.filter(item => item.name.indexOf(query) > -1);

              }, 200);
            }
            if (type === 'risk') {
              _this.loading1 = true;
              this.post(this.api.promote.getRecommendPageList, {
                name: query
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading1 = false;
                  _this.riskList = res.data.object.map(item => ({
                    healthCheckPackageId: item.id,
                    name: item.name,
                    type: item.healthRiskTypeName,
                    belongType: 2
                  }));
                }
              })
              setTimeout(() => {
                _this.loading1 = false;
                _this.riskFilterList = _this.riskList.filter(item => item.name.indexOf(query) > -1);
              }, 200)
            }
            if (type === 'inviolable') {
              _this.loading4 = true;
              this.post(this.api.promote.inviolableList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                search: query
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading4 = false;
                  _this.inviolableFilterList = res.data.object;
                  if (_this.activityInviolableId) {
                    let resArr = _this.inviolableFilterList.filter(item => item.name === query);
                    if (resArr.length > 0) {
                      _this.formModel.inviolableId = resArr[0].id;
                    }
                  }
                }
              })
              /*  setTimeout(() => {
                 _this.loading4 = false;
                 _this.inviolableFilterList = _this.inviolableList.filter(item => item.name.indexOf(query) > -1);
                 console.log(_this.inviolableFilterList)
               }, 200) */
            }
            if (type === 'activeCustomers') { // 参与活动客户
              _this.loading5 = true;
              this.post(this.api.company.companyList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
                hospitalType: '',
                status: 1
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading5 = false;
                  _this.activeCustomersList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading5 = false;
                _this.activeCustomersFilterList = _this.activeCustomersList.filter(item => item.name.indexOf(query) > -1);
              }, 200)
            }
            if (type === 'appointment') { // 关联活动预约
              _this.loadingAppointment = true;
              this.post(this.api.promote.getCompanyBeforeAppointmentPage, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                appointmentName: query,
                companyId: this.formModel.companyId
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loadingAppointment = false;
                  _this.appointmentList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loadingAppointment = false;
                _this.appointmentFilterList = _this.appointmentList.filter(item => item.appointmentName.indexOf(query) > -1);
              }, 200)
            }
            if (type === 'hospital') {
              _this.loading6 = true;
              this.post(this.api.hospitalManager.list, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading6 = false;
                  _this.interpretationList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading6 = false;
                _this.interpretationFilterList = _this.interpretationList.filter(item => item.name.indexOf(query) > -1);
              }, 200)
            }
          }
          /**
           * 搜索内容渲染到下拉框
           * 从 this.dataList1 把数据赋值到 this.options1
           * 只有这样才能起作用
           */

        } else {
          if (type === 'factory') {
            this.activityFilterFactory = [];
          }
          if (type === 'theme') {
            this.activeThemeFilterList = [];
          }
          if (type === 'risk') {
            this.riskFilterList = [];
          }
          if (type === 'inviolable') {
            this.inviolableFilterList = [];
          }
          if (type === 'activeCustomers') { // 参与活动客户
            this.activeCustomersFilterList = [];
          }
          if (type === 'appointment') { // 关联活动预约
            this.appointmentFilterList = [];
          }
          if (type === 'hospital') {
            this.interpretationFilterList = [];
          }
        }
      },
      handleSelect (item, type) {
        if (type === 'factory') {
          this.factoryId = item;
          this.queryMedicine();
        }
        if (type === 'theme') {
          this.formModel.themeId = item;
          this.post(this.api.promote.themeDiseaseInfo, {
            id: item
          }).then(res => {
            if (res.data.code === '200') {
              let resData = res.data.object;
              this.formModel.themeHealthList = resData.themeHealthDtoList;

              // 回显相关检测项
              let colArr = [['deviceId', 'deviceName', 'delField'], []];


              resData.correlationDtoList.forEach(item => { // 回显相关检测项
                item.delField = '删除';
              })
              this.merge(colArr, resData.correlationDtoList);
              this.correlationDtoList = resData.correlationDtoList;

              resData.bindicatorDtoList.forEach(item => { // 回显必测检测项
                item.themeDeviceDtoList.forEach(el => {
                  el.delField = '删除';
                })
                this.merge(colArr, item.themeDeviceDtoList);
              });
              this.themeDeviceTableList1 = resData.bindicatorDtoList.filter(item => item.modelIndex === 0)[0].themeDeviceDtoList; // 回显必测检测项 - 全测指标
              this.themeDeviceTable = resData.bindicatorDtoList.filter(item => item.modelIndex !== 0); // 回显必测检测项 - 任选几项



              this.formModel.recommendSalesScript = resData.recommendSalesScript;
              this.formModel.recommendableProjects = resData.recommendableProjects;
              this.formModel.recommendMedicineRequestDtoList = resData.recommendMedicineRequestDtoList;
              this.formModel.apparatusRequestDtoList = resData.apparatusRequestDtoList;
              this.formModel.sellDrugDtoList = resData.sellDrugDtoList;

              const result = this.typeList.map(item => ({
                ...item,
                value: resData.recommendMedicineRequestDtoList.filter(sItem => item.drugType === sItem.drugType)
              }))
              this.recommendMedicineRequestDtoList = result;
              resData.themeKnowledgeRequestDtoList.forEach(item => {
                item['keyWordList'] = item.keyWord.split(',');
                if (item.knowledgeImageUrls) {
                  this.$set(item, 'knowledgeImage', JSON.parse(item.knowledgeImageUrls));
                }
              })
              this.knowledgeList = resData.themeKnowledgeRequestDtoList.filter(item => item.isImportant === 0);
              this.goodsList = resData.themeKnowledgeRequestDtoList.filter(item => item.isImportant === 1);
            }
          })

        }
        if (type === 'risk') {
          this.riskIds = item;
        }
        if (type === 'inviolable') {
          this.formModel.inviolableId = item;
        }
        if (type === 'activeCustomers') { // 参与活动客户
          this.formModel.companyId = item;
          this.allMultipleSelection = [];
          this.formModel.appointmentId = null;
          this.appointmentFilterList = [];
          this.fetchData();
        }
        if (type === 'appointment') { // 关联活动预约
          this.formModel.appointmentId = item;
        }
        if (type === 'hospital') {
          this.formModel.hospitalId = item;
        }
      },
      // 增加推荐健康风险筛查项目
      handleAddTable (selVal, op) {
        if (op === 'risk') {
          if (selVal.length === 0) {
            this.$message.error('请选择推荐健康风险筛查项目!');
            return
          }
          let temp = this.riskList.filter(item => selVal.some(ele => ele === item.healthCheckPackageId));
          this.formModel.themeHealthList = this.commonFunction.removeDuplicatedItem([...this.formModel.themeHealthList, ...temp], 'healthCheckPackageId');
          this.riskIds = [];
        }
      },
      // 根据活动主题和参与活动厂家查询参与活动药品
      queryMedicine () {
        if (this.factoryId.length === 0) {
          this.$message.error('请至少选择一个参与活动厂家!');
          this.formModel.activityDrugList = [];
          return
        }
        this.post(this.api.promote.activitySellDrugList, {
          ids: this.factoryId,
          themeId: this.formModel.themeId,
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            resData.forEach(item => {
              item['activityDrugAnnexDtos'] = item.sellDrugAnnexDtos;
              item['activityDrugKnowledgeDtos'] = item.sellDrugKnowledgeDtos;
              if (item.advertisingDto) {
                item['activityAdvertisingDrugDto'] = item.advertisingDto;
                item['activityAdvertisingDrugDto']['advertisingId'] = item.activityAdvertisingDrugDto.id
                item.activityAdvertisingDrugDto.id = null;
              }
              item.isUp = 1;
              if (item.activityId) {
                item.activityId = this.formModel.activityId;
              } else {
                item.activityId = this.formModel.activityId;
                item.id = null;
              }

            })
            if (resData.length > 0) {
              this.formModel.activityDrugList = resData;
            } else {
              this.$message.error('该厂将没有参与活动的药品,不能参加活动!');
              this.factoryId = '';
            }
          }
        })
      },
      // 详情
      async getDetail () {
        const { data: res } = await this.post(this.api.promote.activityInfo, { id: this.activityId });
        if (res.code === '200') {
          let resData = res.object;
          let colArr = [['deviceId', 'deviceName', 'delField'], []];
          this.formModel.name = resData.name; // 回显活动名称
          this.formModel.type = resData.themeType; // 回显主题类型
          this.formModel.activityId = resData.id;
          this.formModel.activityDrugList = resData.activityDrugDtoList; // 回显参加活动药品信息
          this.formModel.themeHealthList = resData.themeHealthDtoList; // 回显已选健康筛查项目
          this.formModel.introduce = resData.introduce ? resData.introduce : ''; // 回显活动介绍

          this.formModel.recommendSalesScript = resData.recommendSalesScript;
          this.formModel.recommendableProjects = resData.recommendableProjects;
          this.formModel.beginTime = resData.beginTime;
          this.formModel.finishTime = resData.finishTime;
          this.formModel.activityStudyTime = resData.activityStudyTime;
          this.formModel.activityDrugStudyTime = resData.activityDrugStudyTime;

          // 回显解读医院
          if (resData.hospitalName) {
            this.formModel.hospitalId = resData.hospitalName.id;
            this.interpretationFilterList = [resData.hospitalName];
          }

          // 活动关联检测项及参考值
          resData.correlationDtoList.forEach(item => { // 回显相关检测项
            item.delField = '删除';
          })
          this.correlationDtoList = this.merge(colArr, resData.correlationDtoList);
          resData.bindicatorDtoList.forEach(item => { // 回显必测检测项
            item.themeDeviceDtoList.forEach(el => {
              el.delField = '删除';
            })
            this.merge(colArr, item.themeDeviceDtoList);
          });
          this.themeDeviceTableList1 = resData.bindicatorDtoList.filter(item => item.modelIndex === 0)[0].themeDeviceDtoList; // 回显必测检测项 - 全测指标
          this.themeDeviceTable = resData.bindicatorDtoList.filter(item => item.modelIndex !== 0); // 回显必测检测项 - 任选几项
          if (this.themeDeviceTable.length > 0) {
            let len = this.themeDeviceTable.length;
            this.maxNum = this.themeDeviceTable[len - 1]['modelIndex'] + 1;
          }

          // 回显参与活动客户查询总店
          this.formModel.companyId = resData.companyName.id;
          this.activeCustomersFilterList = [resData.companyName];
          this.handleSelect(resData.companyName.id, 'activeCustomers'); // 回显分店

          this.allMultipleSelection = resData.hospitalIds; // 回显选中的分店
          this.tableBranch = resData.hospitalDtoList;

          // 回显参与活动厂家
          this.factoryId = resData.factoryNames.map(item => item.id);
          this.activityFilterFactory = resData.factoryNames;
          // 回显活动主题
          this.formModel.themeId = resData.themeId;
          this.activeThemeFilterList = [{ id: resData.themeId, name: resData.themeName }];


          // 回显活动关联权益
          let inviolableName = resData.inviolableInfo.name;
          this.remoteMethod(inviolableName, 'inviolable');
          this.activityInviolableId = resData.inviolableInfo.id;

          // 关联活动预约
          if (resData.appointmentId && resData.appointmentId !== 0) {
            let { appointmentId, appointmentName } = resData;
            this.formModel.appointmentId = appointmentId;
            this.appointmentFilterList = [
              { appointmentId: appointmentId, appointmentName: appointmentName }
            ];
          } else {
            this.formModel.appointmentId = null;
          }

          //
          this.formModel.apparatusRequestDtoList = resData.apparatusRequestDtoList;
          this.formModel.sellDrugDtoList = resData.sellDrugDtoList;

          this.formModel.recommendMedicineRequestDtoList = resData.recommendMedicineRequestDtoList;
          const result = this.typeList.map(item => ({
            ...item,
            value: resData.recommendMedicineRequestDtoList.filter(sItem => item.drugType === sItem.drugType)
          }))
          this.recommendMedicineRequestDtoList = result;
          resData.themeKnowledgeRequestDtoList.forEach(item => {
            item['keyWordList'] = item.keyWord.split(',');
            if (item.knowledgeImageUrls) {
              this.$set(item, 'knowledgeImage', JSON.parse(item.knowledgeImageUrls));
            }
          })
          this.knowledgeList = resData.themeKnowledgeRequestDtoList.filter(item => item.isImportant === 0);
          this.goodsList = resData.themeKnowledgeRequestDtoList.filter(item => item.isImportant === 1);
          this.formModel.activityUserInviolableRightsDtos = resData.activityUserInviolableRightsDtos; // 回显C端用户签到权益
        }

      },
      removeRow (data, index, op) {
        data.splice(index, 1);
      },
      // 编辑知识点、活动商品卖点、C端用户签到权益
      editRow (data, index, option) {
        if (option === 'knowledge') {
          this.isShowKnowledge = true;
          this.isShowDetail = true;
          this.knowledgeDataObj = Object.assign({}, { ...data[index], isEdit: true, key: index, });
        }
        if (option === 'goods') {
          this.isShowGoods = true;
          this.isShowDetail = true;
          this.goodsDataObj = Object.assign({}, { ...data[index], isEdit: true, key: index, });
        }
        if (option === 'equity') {
          this.isShowEquity = true;
          this.isShowEquityDetail = true;
          this.equityObj = Object.assign({}, { ...data[index], isEdit: true, key: index, });
          this.inviolableTableData = data;
        }

      },
      // ---------远程搜索必测检测项、相关检测项---------
      remoteMethod2 (query, op) {
        if (query !== '') {
          let _this = this;
          if (op === 'everyItem') {
            _this.loading44 = true;
            this.post(this.api.promote.getDeviceList, {
              name: query,
              pageIndex: 0,
              pageSize: 10
            }).then(res => {
              if (res.data.code === '200') {
                _this.loading44 = false;
                _this.detectList = res.data.object;
              }
            })
            setTimeout(() => {
              _this.loading44 = false;
              _this.detectFilterList = _this.detectList.filter(item => item.name.indexOf(query) > -1);
            }, 200)
          }
          if (op === 'someItem') {
            _this.loading33 = true;
            this.post(this.api.promote.getDeviceList, {
              name: query,
              pageIndex: 0,
              pageSize: 10
            }).then(res => {
              if (res.data.code === '200') {
                _this.loading33 = false;
                _this.detectList = res.data.object;
              }
            })
            setTimeout(() => {
              _this.loading33 = false;
              _this.detectFilterList = _this.detectList.filter(item => item.name.indexOf(query) > -1);
            }, 200)
          }
          // 相关检测项
          if (op === 'detect') {
            _this.loading55 = true;
            this.post(this.api.promote.getDeviceList, {
              name: query,
              pageIndex: 0,
              pageSize: 10
            }).then(res => {
              if (res.data.code === '200') {
                _this.loading55 = false;
                _this.detectList = res.data.object;
              }
            })
            setTimeout(() => {
              _this.loading55 = false;
              _this.detectFilterList = _this.detectList.filter(item => item.name.indexOf(query) > -1);
            }, 200)
          }

        } else {
          if (op === 'everyItem') {
            this.detectFilterList = [];
          }
          if (op === 'someItem') {
            this.detectFilterList = [];
          }
          if (op === 'detect') {
            this.detectFilterList = [];
          }

        }
      },

      handleSelect2 (item, op) {
        if (op === 'detect') {
          this.detectIds = item;
        }
        if (op === 'someItem') {
          this.someDetectIds = item;
        }

      },
      // 必测检测项-动态添加 任选几项
      handleAddItem (num) {
        this.themeDeviceTable.push({
          modelIndex: num,
          num: undefined,
          themeDeviceDtoList: []
        });
      },
      /*
* 增加推全测指标、任意几项指标、相关检测项,推荐健康风险筛查项目
*
* @param selVal {string} 文件名
* @param op {string} 操作类型
* @param index {number} 数组下标
* @param fillNum {number} 任意几项
* @param modelIndex {number} 删除后剩下的下标
*/
      handleAddSelectVal (selVal, op, index, fillNum, modelIndex) {
        // 全测指标
        if (op === 'everyItem') {
          if (selVal === '') {
            this.$message.error('请选择推荐检测项!');
            return
          }
          if (this.themeDeviceTableList1.some(item => item.deviceId === selVal)) {
            this.$message.error('推荐检测项不能重复添加!');
            this.everyDetectIds = '';
            return
          }
          this.post(this.api.promote.getReferenceInfo, { deviceId: selVal })
            .then(res => {
              if (res.data.code === '200') {
                let colArr = [['deviceId', 'deviceName', 'delField'], []];
                res.data.object.forEach(item => {
                  item.delField = '删除';
                  item.bindicator = 1;
                  item.modelIndex = 0;
                  item.num = 0;
                })
                let resData = res.data.object;
                if (resData.length === 0) {
                  this.$message.error('该检测项的检测指标为空,请选择其它检测项目!');
                  this.everyDetectIds = '';
                  return;
                }
                let temp = [...this.themeDeviceTableList1, ...resData];
                let resTable = this.merge(colArr, temp); // 合并单元格
                this.themeDeviceTableList1 = resTable;
                this.everyDetectIds = '';
              }

            })
        }
        // 任意测几项
        if (op === 'someItem') {
          if (selVal === '') {
            this.$message.error('请选择推荐检测项!');
            return
          }
          if (this.themeDeviceTable[index].themeDeviceDtoList.some(item => item.deviceId === selVal)) {
            this.$message.error('推荐检测项不能重复添加!');
            this.themeDeviceTable[index].someDetectIds = '';
            return
          }
          this.post(this.api.promote.getReferenceInfo, { deviceId: selVal })
            .then(res => {
              if (res.data.code === '200') {
                let colArr = [['deviceId', 'deviceName', 'delField'], []];
                res.data.object.forEach(item => {
                  item.delField = '删除';
                  item.bindicator = 1;
                  item.modelIndex = modelIndex;
                  item.num = fillNum;
                })
                let resData = res.data.object;
                if (resData.length === 0) {
                  this.$message.error('该检测项的检测指标为空,请选择其它检测项目!');
                  this.themeDeviceTable[index].someDetectIds = '';
                  return;
                }
                let temp = [...this.themeDeviceTable[index].themeDeviceDtoList, ...resData];
                let resTable = this.merge(colArr, temp); // 合并单元格
                this.themeDeviceTable[index].themeDeviceDtoList = resTable;
                this.themeDeviceTable[index].someDetectIds = '';
              }

            })
        }
        // 相关检测项
        if (op === 'detect') {
          if (selVal === '') {
            this.$message.error('请选择推荐检测项!');
            return
          }
          if (this.correlationDtoList.some(item => item.deviceId === selVal)) {
            this.$message.error('推荐检测项不能重复添加!');
            this.detectIds = '';
            return
          }
          this.post(this.api.promote.getReferenceInfo, { deviceId: selVal })
            .then(res => {
              if (res.data.code === '200') {
                let colArr = [['deviceId', 'deviceName', 'delField'], []];
                res.data.object.forEach(item => {
                  item.delField = '删除';
                  item.bindicator = 0;
                  item.modelIndex = -1;
                  item.num = 0;
                })
                let resData = res.data.object;
                if (resData.length === 0) {
                  this.$message.error('该检测项的检测指标为空,请选择其它检测项目!');
                  this.detectIds = '';
                  return;
                }
                let temp = [...this.correlationDtoList, ...resData];
                let resTable = this.merge(colArr, temp); // 合并单元格
                this.correlationDtoList = resTable;
                this.detectIds = '';
              }

            })

        }
        // 已选健康筛查项目
        if (op === 'risk') {
          if (selVal === '') {
            this.$message.error('请选择推荐健康风险筛查项目!');
            return
          }
          if (this.formModel.themeHealthDtoList.some(item => item.healthCheckPackageId === selVal)) {
            this.$message.error('推荐健康风险筛查项目不能重复添加!');
            this.riskIds = '';
            return
          }
          let temp = this.riskList.filter(item => item.healthCheckPackageId == selVal);
          this.formModel.themeHealthDtoList = [...this.formModel.themeHealthDtoList, ...temp];
          this.riskIds = '';

        }
      },
      // 删除已选推荐检测项、已选健康筛查项目
      delRowItem (table, op, index, fillNum) {
        table.splice(index, 1);

      },
      // 删除已选检测项 带合并单元格
      delMergeRow (table, row, op, parentIndex) {
        if (op === 'someItem') {
          this.themeDeviceTable[parentIndex].themeDeviceDtoList = table.filter(item => item.deviceId !== row.deviceId);
        }
        if (op === 'everyItem') {
          this.themeDeviceTableList1 = table.filter(item => item.deviceId !== row.deviceId)
        }
        if (op === 'detect') {
          this.correlationDtoList = table.filter(item => item.deviceId !== row.deviceId)
        }
      },
      changeItemVal (val) {
        this.themeDeviceTable.forEach(item => {
          item.themeDeviceDtoList.forEach(el => {
            el.num = item.num
          })
        })
      },
      // 合并行计算
      merge (colArr, list) {
        let allProps = [];
        colArr.forEach((props, index) => {
          allProps.push(...props);
          list = this.getLevel(props, allProps, list);
        });
        return list;
      },
      // 组装层
      getLevel (props, allProps, list) {
        var rowKey = {};
        for (var item of list) {
          let propInfo = this.getPropStr(allProps, item);
          if (rowKey[propInfo.key]) {
            rowKey[propInfo.key].children.push(item);
          } else {
            let obj = propInfo;
            obj.children = [item];
            rowKey[propInfo.key] = obj;
          }
        }
        let info = [];
        for (var key in rowKey) {
          rowKey[key].children.forEach((item, index) => {
            if (index == 0) {
              item = Object.assign(
                item,
                this.getMergeInfo(props, rowKey[key].children.length)
              );
            } else {
              item = Object.assign(item, this.getMergeInfo(props, 0));
            }
            info.push(item);
          });
        }
        return info;
      },
      // 获取合并信息
      getMergeInfo (props, num) {
        let obj = {};
        props.forEach(item => {
          obj[item + "_merge"] = {
            rowspan: num,
            colspan: 1
          };
        });
        return obj;
      },
      // 把属性的值拼接在一起,并和属性的值一起返回。
      getPropStr (props, info) {
        let obj = {};
        let propStr = props.map(item => {
          obj[item] = info[item];
          return info[item];
        });
        obj.key = propStr.toString();
        return obj;
      },
      // 表格合并
      handleSpan ({ row, column, rowIndex, columnIndex }) {
        if (row[column.property + "_merge"]) {
          return row[column.property + "_merge"];
        } else {
          return { rowspan: 1, colspan: 1 };
        }
      },
    },
    created () {
      if (this.dataThemeObj) {
        this.title = '编辑主题任务发布';
        this.activityId = this.dataThemeObj.id;
        this.getDetail();
      } else {
        this.activityId = null;
      }
    },
    components: {
      'equipment-dialog': equipmentDialog,
      'shop-dialog': shopDialog,
      'medicine-dialog': medicineDialog,
      'knowledge-dialog': knowledgeDialog,
      'goods-dialog': goodsDialog,
      'equity-dialog': equityDialog, // C端用户签到权益
      VueNeditorWrap
    },
    computed: {
      ...mapGetters(['fileUpload'])
    }
  }
</script>
<style scoped lang="scss">
  .knowledge-box {
    width: 100%;
    .el-timeline-item {
      padding-bottom: 0;
      span {
        padding-right: 10px;
        padding-bottom: 10px;
        border-right: 1px solid #ebeef5;
        width: calc(100% - 150px);
      }
    }
    /deep/ .el-timeline-item__wrapper {
      top: -10px;
      padding-left: 20px;
      .knowledge-main {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ebeef5;
      }
      .el-timeline-item__timestamp.is-bottom {
        margin-top: 0;
      }
      .knowledgeImage-list {
        display: flex;
        flex-wrap: wrap;
        li {
          position: relative;
          .del {
            position: absolute;
            z-index: 1;
            right: 0;
            top: 0;
            font-size: 18px;
            color: #f00;
            cursor: pointer;
            display: inline-block;
          }
        }
      }
      .el-image {
        overflow: unset;
        border: 1px dashed #999;
        margin-right: 10px;
        text-align: center;
        margin-top: 10px;
        img {
          height: 100px;
          width: 100px;
          margin-top: 10px;
        }
      }
      .remove {
        font-size: 20px;
        color: #f00;
        cursor: pointer;
      }
    }
  }
  .w-500 {
    width: 500px;
  }
  .table-cell {
    td {
      padding: 3px 10px;
      border-bottom: 1px solid #ebeef5;
      border-right: 1px solid #ebeef5;
      &.first-td {
        border-left: 1px solid #ebeef5;
      }
    }
  }
  .card-box {
    /deep/ .el-card__header {
      padding: 10px 20px;
      .fill-box {
        font-size: 14px;
        font-weight: bold;
        padding-right: 20px;
      }
    }
    .num {
      width: 100px;
      /deep/ .el-input__inner {
        border: none;
        border-bottom: 1px solid #999;
        border-radius: 0;
        width: 100px;
        color: #f00;
        font-weight: bold;
        text-align: center;
      }
    }
  }
</style>
